<?php
require_once("db/db_connector.php");
require_once("db/db_picture.php");
require_once("db/db_paradise.php");
require_once("libs/phpthumb/ThumbLib.inc.php");

define("DATA_DIR", "data");
define("PUBLIC_DATA_DIR", "/my-paradise/data"); /* change this to public data directory */

function filename_add_suffix($filename, $suffix)
{
	$name_end = strrpos($filename, ".");
	$name = substr($filename, 0, $name_end);
	$extension = substr($filename, $name_end);
	
	return "$name$suffix$extension";
}

$file_uploaded = FALSE;

$url = NULL;
$thumb_big = NULL;
$thumb_small = NULL;

$paradise_id = $_POST["paradise_id"];
$return_url = "paradise.php?id=$paradise_id";

// Upload picture and create thumbnails.
if (isset($_FILES["picture"]) and $_FILES["picture"]["error"] == 0) {
	$tmpname = $_FILES["picture"]["tmp_name"];
	$filename = time()."-".$_FILES["picture"]["name"];
	$filepath = DATA_DIR."/$filename";
	
	if (move_uploaded_file($tmpname, $filepath)) {
		$thumb = PhpThumbFactory::create($filepath);
		$thumb->adaptiveResize(480, 360);
		$thumb->save(filename_add_suffix($filepath, "-b"));
		$thumb->adaptiveResize(160, 120);
		$thumb->save(filename_add_suffix($filepath, "-s"));
		
		$url = PUBLIC_DATA_DIR."/$filename";
		$thumb_big = PUBLIC_DATA_DIR."/".filename_add_suffix($filename, "-b");
		$thumb_small = PUBLIC_DATA_DIR."/".filename_add_suffix($filename, "-s");
		
		$file_uploaded = TRUE;
	}
}

if (!$file_uploaded) {
	$error = 2;
	$return_url .= "&error=$error";	
	header("Location: $return_url");
	exit();
}

$_POST["url"] = $url;
$_POST["thumb_big"] = $thumb_big;
$_POST["thumb_small"] = $thumb_small;

// Database Access Begins ---------------------------------------- //
$con = get_db_con();
$result = insert_picture($con, $_POST);

// Set as a main picture of the paradise
if ($_POST["main_picture"] == "true" and $result > 0) {
	$paradise = get_paradise($con, $_POST["paradise_id"]);
	$paradise["picture_id"] = $result;
	$result = update_paradise($con, $paradise);
}
close_db_con();
// Database Access Ends ------------------------------------------ //

if ($result <= 0) {
	$error = 3;
}

if (isset($error)) {
	$return_url .= "&error=$error";
}

$return_url .= "#pictures";

header("Location: $return_url");